package com.foreknow.dao.impl;

import com.foreknow.bean.Admin;
import com.foreknow.dao.AdminDao;
import com.foreknow.mapping.EntityMapping;
import com.foreknow.mapping.MappingFactory;

import java.sql.SQLException;
import java.util.List;

public class AdminDaoImpl extends BaseDao implements AdminDao {

    //添加管理员信息
    @Override
    public boolean save(Admin admin) throws SQLException{
        int isRight = jdbcTemplate.update("insert into admin(id,username,password,age,school) values(?,?,?,?,?)",admin.getId(),admin.getUsername(),admin.getPassword(),admin.getAge(),admin.getSchool());
        return isRight==1;
    }

    //根据id查询管理员信息
    @Override
    public Admin queryById(Integer id) throws SQLException{
        EntityMapping entityMapping = mappingFactory.getMapping(mappingFactory.ADMIN_MAPPING);
        List<Object> list = jdbcTemplate.query("select * from admin where id = ?",entityMapping,id);
        if(list.size()>0){
            return (Admin)list.get(0);
        }
        return null;
    }

    //修改
    @Override
    public boolean update(Admin admin) throws SQLException{
        int isRight = jdbcTemplate.update("update admin set username = ?,password = ?,age = ?,school = ? where id = ?",admin.getUsername(),admin.getPassword(),admin.getAge(),admin.getSchool(),admin.getId());
        return isRight==1;
    }

    //根据id删除
    @Override
    public boolean delete(Integer id) throws SQLException{
        int isRight = jdbcTemplate.update("delete from admin where id=?",id);
        return isRight==1;
    }

    //查询所有的用户信息
    @Override
    public List<Object> getQueryAll() throws SQLException{
        EntityMapping entityMapping = mappingFactory.getMapping(mappingFactory.ADMIN_MAPPING);
        List<Object> list = jdbcTemplate.query("select * from admin",entityMapping);
        return list;
    }

    @Override
    public Admin isCheckLogin(String username, String password) throws SQLException {
        String sql = "select * from admin where username=? and password=?";
        EntityMapping mapping = mappingFactory.getMapping(MappingFactory.ADMIN_MAPPING);
        List<Object> list = jdbcTemplate.query(sql,mapping,username,password);
        if(list.size()>0){
            return (Admin) list.get(0);
        }
        return null;
    }
}